package com.snail.aiChat.config;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.snail.aiChat.functioncalling.CourseTools;
import com.snail.aiChat.memory.RedisChatMemoryRepository;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.ChatMemoryRepository;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.ai.zhipuai.ZhiPuAiChatModel;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;



/**
 * @author Monica
 * @date 2025/6/28 13:44
 */
@Configuration
public class CommonConfiguration {
    @Bean
    public ChatMemoryRepository chatMemoryRepository(StringRedisTemplate stringRedisTemplate) {
        // 默认情况下，如果尚未配置其他存储库，则 Spring AI 会自动配置ChatMemoryRepository类型的 beanInMemoryChatMemoryRepository可以直接在应用程序中使用。
        // 这里手动创建内存聊天记忆存储库
        return new RedisChatMemoryRepository(stringRedisTemplate, new ObjectMapper());
    }

    @Bean
    public ChatMemory chatMemory(ChatMemoryRepository chatMemoryRepository) {
        // 注册聊天上下文记忆机制
        return MessageWindowChatMemory
                .builder()
                .chatMemoryRepository(chatMemoryRepository)
                .maxMessages(20)   // 聊天记忆条数
                .build();
    }

    @Bean
    public ChatClient deepseekChatClient(ZhiPuAiChatModel chatModel, ChatMemory chatMemory, CourseTools courseTools) {
        return ChatClient
                .builder(chatModel)
                .defaultSystem("你是一个在线学习的助手，能提供一些推荐课程，也能回答用户的问题，你回答的内容一定要是markdown格式。" +
                        "在回答推荐课程的时候，请你把链接改成/course/learn/${courseId}的形式")
                .defaultAdvisors(
                        new SimpleLoggerAdvisor(),  // 配置日志Advisor
                        MessageChatMemoryAdvisor.builder(chatMemory).build()    // 绑定上下文记忆
                ).defaultTools(courseTools)
                .build();
    }

}
